require 'digest/md5'
require 'net/http'
require 'open-uri'
require 'iconv'
require 'yaml'
require 'erb'
require './crack'
module TaobaoAPI
taobao_config_file = File.dirname(__FILE__) + '/tao.yml'
@config = YAML.load(ERB.new(File.read(taobao_config_file)).result)

class <<self
#组装参数
def paramArray(joins={})
  {
    'api_key' => @config['api_key'].to_s,
    'format'=> @config['format'], 
    'v' => @config['v'].to_s,
    'timestamp' => timestamp
  }.merge(joins)
end

def timestamp
  Time.now.strftime("%Y-%m-%d %H:%M:%S")
end 
#生成签名
def sign(param,sercetCode)
	  array = param.sort {|a,b|a.to_s <=> b.to_s}
  	i = 0
  	str = sercetCode
  	while i < param.length()
    	temp = array[i]
      	str = str + temp[0].to_s + temp[1].to_s
      	i = i + 1    
  	end
  	str = Digest::MD5.hexdigest(str)
  	return str.upcase()
end
 
#组装请求参数
def createRequestParam(paramArray)
	array = paramArray.sort {|a,b|a.to_s <=> b.to_s}
  	i = 0
  	str = ''
  	while i < paramArray.length()
    	temp = array[i]
    	str = str + temp[0].to_s + '=' + temp[1].to_s + '&'
    	i = i + 1    
  	end
  	return str
end
 
#URL encode
def URLEncode(str)
	return str.gsub!(/[^\w$&\-+.,\/:;=?@]/) { |x| x = format("%%%x", x[0])}  
end
 
#把str的编码转化为GBK编码
def to_gbk(str)
	Iconv.iconv("GBK//IGNORE","UTF-8//IGNORE",str).to_s
end

def generate_url(paramArray)
  case @config['envhost']
  when 'sandbox'
    "http://gw.api.tbsandbox.com/router/rest?" + createRequestParam(paramArray)+'sign='+ sign(paramArray,@config['secret_key'])
  when 'prod'
    "http://gw.api.taobao.com/router/rest?" + createRequestParam(paramArray)+'sign='+ sign(paramArray,@config['secret_key'])
 end
end

def parse_result(result)
    case @config['format']
    when 'xml'  
      Crack::XML.parse(result) || Crack::XML.parse(result)
    when 'json'
      Crack::JSON.parse(result)
    end
end
  
def get_with(joins={})
  url = generate_url(paramArray(joins))
	parsedURL = URI.parse(URLEncode(url))
 begin
  #请求生成的URL，把结果输出
 	Net::HTTP.version_1_2
 	open(parsedURL) do |http|
      parse_result(http.read)
  end
 rescue Exception => e
   puts e.message
   raise e
 end
 
	
end
end
end